#include "docfile.h"
#include <QtWidgets>
#include <QFileInfo>
#include <QByteArray>
#include <QTextCodec>

DocFile::DocFile()
{
    setAttribute(Qt::WA_DeleteOnClose);
    isUntitled = false;
}

void DocFile::newFile(void)
{
    static int sequenceNumber = 1; //记录文档序号
    isUntitled = true;
    curFile = tr("文档 %1").arg(sequenceNumber++);
    setWindowTitle(curFile + "*" + tr( " -textEdit")); //设置标题
    connect(document(), SIGNAL(contentsChanged()), this, SLOT(documentWasModified()));
}

QString DocFile::userFriendlyCurrentFIle()
{
    return strippedName(curFile);
}

bool DocFile::loadFile(const QString &fileName)
{
    if (fileName.isEmpty())  //检测文件名是否为空
    {
        return false;
    }
    if (!QFile::exists(fileName))  //检测文件是否存在
    {
        return false;
    }
    //打开指定的文件，并读取内容到编辑器
    QFile file(fileName);
    if (!file.open(QFile::ReadOnly))
    {
        return false;
    }
    QByteArray data = file.readAll();
    QTextCodec *codec = Qt::codecForHtml(data);
    QString str = codec->toUnicode(data);
    //判断是富文本还是普通文本
    if (Qt::mightBeRichText(str))
    {
        this->setHtml(str);
    }
    else
    {
        str = QString::fromLocal8Bit(data);
        this->setPlainText(str);
    }
    //设置当前文件
    setCurrentFileName(fileName);
    //关联文档内容改变信号
    connect(document(), SIGNAL(contentsChanged()), this, SLOT(documentWasModified()));

    return true;
}

//获取文件路径，修改窗口标题
void DocFile::setCurrentFileName(const QString &fileName)
{
    curFile = QFileInfo(fileName).canonicalFilePath();
    isUntitled = false;
    document()->setModified(false);
    setWindowModified(false);
    setWindowTitle(userFriendlyCurrentFIle() + "[*]");
}

bool DocFile::save(void)
{
    if (isUntitled)
    {
        return saveAs();
    }
    else
    {
        return saveFile(curFile);
    }
}

bool DocFile::saveAs(void)
{
    QString fileName = QFileDialog::getSaveFileName(this, tr("另存为..."), curFile, tr("HTML 文档(*.htm *.html);;所有文件(*.*)"));
    if (fileName.isEmpty())
    {
        return false;
    }
    return saveFile(fileName);
}

bool DocFile::saveFile(QString fileName)
{
    QFileInfo fileinfo = QFileInfo(fileName);
    QString fileSuffix = fileinfo.suffix();
    if (fileSuffix.isEmpty())
    {
        fileName += ".html";
    }
    QTextDocumentWriter writer(fileName);
    bool success = writer.write(this->document());
    if (success)
    {
        setCurrentFileName(fileName);
    }

    return success;
}

void DocFile::mergeFormat(QTextCharFormat &charFormat)
{
    QTextCursor textCursor = this->textCursor();
    if (!textCursor.hasSelection())
    {
        textCursor.select(QTextCursor::WordUnderCursor);
    }
    textCursor.mergeCharFormat(charFormat);
    this->mergeCurrentCharFormat(charFormat);
}

void DocFile::textAlign(int align)
{
    switch (align) {
    case 1:
        this->setAlignment(Qt::AlignLeft | Qt::AlignAbsolute);
        break;
    case 2:
        this->setAlignment(Qt::AlignCenter);
        break;
    case 3:
        this->setAlignment(Qt::AlignRight | Qt::AlignAbsolute);
        break;
    case 4:
        this->setAlignment(Qt::AlignJustify);
        break;
    default:
        break;
    }
}

void DocFile::closeEvent(QCloseEvent *event)
{
    if (toBeSaved())
    {
        event->accept();
    }
    else
    {
        event->ignore();
    }
}

bool DocFile::toBeSaved()
{
    if (!document()->isModified())
    {
        return true;
    }
    QMessageBox::StandardButton ret;
    ret = QMessageBox::warning(this, tr("text editor"), tr("文档'%1'已被修改，需要保存吗？").arg(userFriendlyCurrentFIle()), QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel);
    if (ret == QMessageBox::Save)
    {
        return save();
    }
    else if (ret == QMessageBox::Cancel)
    {
        return false;
    }

    return true;
}

void DocFile::documentWasModified(void)
{
    setWindowModified(document()->isModified());
}

QString DocFile::strippedName(QString &fullFileName)
{
    return QFileInfo(fullFileName).fileName();
}



